package com.baizhi.serviceimpl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baizhi.annotation.AddLog;
import com.baizhi.dao.UserMapper;
import com.baizhi.entity.User;
import com.baizhi.entity.UserExample;
import com.baizhi.service.UserService;
import com.baizhi.util.AliyunOSSUtil;
import com.baizhi.util.UUIDUtil;
import com.baizhi.vo.CommonQueryPageVO;
import com.baizhi.vo.CommonVO;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;


@Service
@Transactional
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Resource
    UserMapper userMapper;

    @Resource
    HttpServletRequest request;

    @Override
    public HashMap<String, Object> queryAllPage(Integer page, Integer pageSize) {


        HashMap<String, Object> map = new HashMap<>();
        //设置当前页数
        map.put("page",page);

        //设置查询条件对象
        UserExample example = new UserExample();

        //查询总条数
        int count = userMapper.selectCountByExample(example);

        //设置总条数
        map.put("total",count);

        //创建分页对象  参数：起始条数，数据数
        RowBounds rowBounds = new RowBounds((page-1)*pageSize,pageSize);

        //根据分页查询数据
        List<User> users = userMapper.selectByExampleAndRowBounds(example, rowBounds);

        //设置数据
        map.put("rows",users);

        return map;
    }

    @Override
    public CommonQueryPageVO queryAllPages(Integer page, Integer pageSize) {

        UserExample example = new UserExample();
        int total = userMapper.selectCountByExample(example);
        RowBounds rowBounds = new RowBounds((page-1)*pageSize,pageSize);

        List<User> users = userMapper.selectByExampleAndRowBounds(example, rowBounds);

        return new CommonQueryPageVO(page,total,users);
    }

    @AddLog(value = "修改用户信息")
    @Override
    public CommonVO updates(User user) {
        /*CommonVO commonVO = new CommonVO();
        try {
            userMapper.updateByPrimaryKeySelective(user);
            commonVO.setMessage("修改成功");
            commonVO.setStatus(200);
        } catch (Exception e) {
            e.printStackTrace();
            commonVO.setMessage("修改失败");
            commonVO.setStatus(400);
        }
        return commonVO;*/

        CommonVO commonVO = new CommonVO();
        try {
            userMapper.updateByPrimaryKeySelective(user);
            return CommonVO.success();
        } catch (Exception e) {
            e.printStackTrace();
            return CommonVO.faild();
        }
    }

    @Override
    public void add(User user) {
        log.info("user service 获取用户数据:{}",user);
        user.setId(UUIDUtil.getUUID());
        user.setStatus("1");
        user.setCreateTime(new Date());
        log.info("user service 调用dao添加用户数据:{}",user);
        userMapper.insertSelective(user);
    }

    @Override
    public String uploadHeadImg(MultipartFile headImg) {

        //1.获取文件名
        String filename = headImg.getOriginalFilename();

        //新文件名
        String newName = new Date().getTime()+"-"+filename;
        //2.获取绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("/upload/headImg");

        File file = new File(realPath);

        //文件夹不存在
        if(!file.exists()){
            file.mkdirs();     //创建文件夹
        }
        String message = null;
        //3.文件上传
        try {
            headImg.transferTo(new File(newName,realPath));
            //返回文件名
            message = newName;
        } catch (IOException e) {
            e.printStackTrace();
            message = newName;
        }

        return message;
    }

    @Override
    public String uploadHeadImgAliyun(MultipartFile headImg) {

        //1.获取文件名
        String fileName = headImg.getOriginalFilename();
        //新文件名
        String newName = new Date().getTime()+"-"+fileName;

        //=========================================

        //配置存储空间名
        String bucketName = "yingx-c";
        //配置文件名
        String objectName = "userImg/"+newName;
        //拼接图片的网络路径
        String netPath = "https://yingx-c.oss-cn-beijing.aliyuncs.com/"+objectName;


        //=========================================

        String message = null;
        //3.文件上传
        try {
            AliyunOSSUtil.uploadfileBytes(bucketName,objectName,headImg);
            //返回文件名
            message = netPath;
        } catch (Exception e) {
            e.printStackTrace();
            message = netPath;
        }

        return message;

    }

    @Override
    public User queryById(String id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public void delete(User user) {

        //1. 删除文件
        //根据文件信息
        User user1 = userMapper.selectOne(user);
        //获取图片网络路径
        String headImg = user1.getHeadImg();

        //字符串处理
        String imgPath = headImg.replace("https://oss-cn-beijing.aliyuncs.com/ ", "");

        AliyunOSSUtil.deleteFile("yingx-c",imgPath);

        //2. 删除数据
        userMapper.delete(user);
    }


    @Override
    public HashMap<String, Object> update(User user) {

        HashMap<String, Object> map = new HashMap<>();
        try {
            userMapper.updateByPrimaryKeySelective(user);
            map.put("message","修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("message","修改失败");
        }
        return map;
    }

}
